﻿using System;
using System.Windows;
using System.Windows.Forms;
using System.IO;
using System.Windows.Threading;

namespace RPNcalc {

  public partial class MainWindow : Window {

    public MainWindow() {
      InitializeComponent();
      DataContext = calc_;
      this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    private void MainWindow_Loaded(object sender, RoutedEventArgs e) {
      timer_ = new DispatcherTimer(DispatcherPriority.Normal, this.Dispatcher);
      timer_.Tick += new EventHandler(this.Tick);
    }

    private void Load_Click(object sender, RoutedEventArgs e) {
      OpenFileDialog dlg = new OpenFileDialog();
      if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        TextReader reader = new StreamReader(dlg.FileName);
        WordEntry entry;
        while ( (entry =WordEntry.FromString(reader.ReadLine())) != null ) {
          calc_.Edit(entry.Key, entry.Value);
        }
        reader.Close();
        calc_.Word = "";
        calc_.Command = "";
      }
    }

    private void Save_Click(object sender, RoutedEventArgs e) {
      SaveFileDialog dlg = new SaveFileDialog();
      if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
        TextWriter writer = new StreamWriter(File.OpenWrite(dlg.FileName));
        foreach(WordEntry entry in calc_.Dictionary) {
          writer.WriteLine(entry);
        }
        writer.Close();
      }
    }

    private void Exit_Click(object sender, RoutedEventArgs e) {
      Close();
    }

    private void Edit_Click(object sender, RoutedEventArgs e) {
      calc_.Edit(Word.Text, Command.Text);
    }

    private void Exec_Click(object sender, RoutedEventArgs e) {
      switch ( Delay.SelectedIndex ) {
      case 0:  timer_.Interval = TimeSpan.FromMilliseconds(1000); break;
      case 1:  timer_.Interval = TimeSpan.FromMilliseconds( 500); break;
      case 2:  timer_.Interval = TimeSpan.FromMilliseconds( 250); break;
      default: timer_.Interval = TimeSpan.FromMilliseconds(  50); break;
      }
      Exec.IsEnabled = false;
      timer_.Start();
    }

    private void Tick(object sender, EventArgs e) {
      if ( !calc_.StepExec() ) {
        timer_.Stop();
        Exec.IsEnabled = true;
      }
    }

    private Calculator calc_ = new Calculator();
    private DispatcherTimer timer_;

  }
}
